//
//  YQUsrInfo.swift
//  WeiBOSina
//
//  Created by a on 16/3/1.
//  Copyright © 2016年 CUM. All rights reserved.
//

import UIKit


 /*
    归档

*/

class YQUsrInfo: NSObject,NSCoding{

    ///access_token	string	用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    ///expires_in	string	access_token的生命周期，单位是秒数。//不能为NSTimeInterVal
    var expires_in: NSTimeInterval = 0
    ///remind_in	string	access_token的生命周期（该参数即将废弃，开发者请使用expires_in）。
    ///uid	string	当前授权用户的UID。
    var uid: String?
    
    ///profile_image_url	string	用户头像地址（中图），50×50像素
    var profile_image_url: String?
    ///screen_name	string	用户昵称
    var screen_name: String?

    //重写构造方法，KVC赋值
    init(dict:[String:NSObject]){
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    
    
    //实现归档的方法
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(profile_image_url, forKey: "profile_image_url")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        self.access_token = aDecoder.decodeObjectForKey("access_token") as? String
        self.access_token = aDecoder.decodeObjectForKey("expires_in") as? String
        self.access_token = aDecoder.decodeObjectForKey("uid") as? String
        self.access_token = aDecoder.decodeObjectForKey("profile_image_url") as? String
        self.access_token = aDecoder.decodeObjectForKey("screen_name") as? String
    }
    
    //自己封装的归档的方法
    func save(fileName:String){
        
        let docPath:String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true).last!
        
        let path = (docPath as NSString).stringByAppendingPathComponent(fileName)
        
        print(path)
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
    }
    
    //有可能不一定存在的情况
    class func read(fileName:String)->YQUsrInfo?{
        let docPath:String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true).last!
        
        let path = (docPath as NSString).stringByAppendingPathComponent(fileName)
        
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? YQUsrInfo
        
    }
    
}
